package com.yeswater.redis7.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {
	
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	
	/**
	 * 设置缓存key的过期时间并进行随机化处理
	 *
	 * @param key   缓存key
	 * @param value 缓存value
	 */
	public void setWithRandomExpire(String key, Object value) {
		// 生成一个随机的过期时间，范围在[240, 300]s之间
		long randomExpireTime = ThreadLocalRandom.current().nextLong(60) + 240;
		redisTemplate.opsForValue().set(key, value, randomExpireTime, TimeUnit.SECONDS);
	}
	
	// 业务
	public void bizFunc(String[] args) {
		// 预热缓存
		warmUpCache();
		
		String value = getFromCache("key1");
		System.out.println("从缓存中获取的值：" + value);
	}
	
	/**
	 * 模拟缓存预热
	 */
	public void warmUpCache() {
		redisTemplate.opsForValue().set("key1", "value1");
		redisTemplate.opsForValue().set("key2", "value2");
		redisTemplate.opsForValue().set("key3", "value3");
	}
	
	
	public String getFromCache(String key) {
		return (String) redisTemplate.opsForValue().get(key);
	}
	
}
